<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">

			<el-form-item label="合同编号" prop="expenseCode">
				<el-input v-model="queryParams.contractCode" placeholder="请输入合同编号"></el-input>
			</el-form-item>
			<el-form-item label="用户名称" prop="uid">
				<el-select v-model="queryParams.uid" filterable placeholder="请选择用户">
					<el-option v-for="item in userData" :key="item.userId" :label="item.nickName" :value="item.userId">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="报销时间" prop="timeData">
				<el-date-picker v-model="timeData" type="daterange" range-separator="至" start-placeholder="开始日期"
					end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="timeChange">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="文件名称" prop="fileName">
				<el-input v-model="queryParams.fileName" placeholder="请输入文件名称"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		

		<!-- 按钮 -->
		<el-row :gutter="10" class="mb8" >
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-download" size="mini" :disabled="multiple"
					@click="handleDownload" >批量下载
				</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<!-- 主表 -->
		<el-table v-loading="loading" :data="contractFileList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="合同编号" align="center" prop="contractCode" />
			<el-table-column label="用户名称" align="center" prop="nickName" />
			<el-table-column label="签约时间" align="center" >
				<template slot-scope="scope">
					{{parseTime(scope.row.businessDate,'{y}-{m}-{d}')}}
				</template>
			</el-table-column>
			<el-table-column label="附件名称" align="center" prop="fileName" />
			<el-table-column label="附件" align="center" prop="file">
				<template slot-scope="scope">
					<el-image v-if="scope.row.suffix != 'pdf'" style="width: 50px; height: 50px"
						:src="upload.baseUrl + scope.row.file" :preview-src-list="[upload.baseUrl + scope.row.file]">
					</el-image>
					<div v-else class="file-pdf" @click="PdfPreview(upload.baseUrl + scope.row.file)">
						<img src="../../../assets/images/pdf.png" alt="" />
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-download" @click="handleFileDownload(scope.row)">
						下载
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<el-dialog custom-class="pdfPreview" title="PDF预览" :visible.sync="filePdfShow" width="100vw" append-to-body>
			<iframe :src="filePdfUrl" frameborder="0"></iframe>
		</el-dialog>
	</div>
</template>

<script>
import { saveAs } from 'file-saver'
import JSZip from 'jszip';
	import {
		getContractFileList,
		getBxExpenseFile,
		delBxExpenseFile,
		addBxExpenseFile,
		updateBxExpenseFile
	} from "@/api/contract/contractFiles";

	


	import {
		listUser
	} from "@/api/system/user"

	export default {
		name: "BxExpenseFile",
		data() {
			return {
				//选取的数据
				selectedList:[],
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 报销附件表格数据
				contractFileList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 用户数据
				userData: [],
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					expenseId: null,
					recordId: null,
					file: null,
					fileName: null,
					createdTime: null,
					expenseCode: null,
					startTime: null,
					endTime: null,
				},
				// 查询条件时间
				timeData: [],
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					expenseId: [{
						required: true,
						message: "主编id不能为空",
						trigger: "blur"
					}],
					recordId: [{
						required: true,
						message: "明细表id不能为空",
						trigger: "blur"
					}],
					file: [{
						required: true,
						message: "附件不能为空",
						trigger: "blur"
					}],
					fileName: [{
						required: true,
						message: "附件名称不能为空",
						trigger: "blur"
					}],
					createdTime: [{
						required: true,
						message: "创建时间不能为空",
						trigger: "blur"
					}]
				},
				upload: {
					// 回显
					baseUrl: process.env.VUE_APP_BASE_API,
				},
				// PDF链接
				filePdfUrl: '',
				// PDF预览弹窗
				filePdfShow: false
			};
		},
		created() {
			this.getUserData();
			this.getList();
		},
		methods: {
			/** 查询报销附件列表 */
			getList() {
				this.loading = true;
				getContractFileList(this.queryParams).then(response => {
					this.contractFileList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 获取用户列表
			getUserData() {
				listUser().then(res => {
					this.userData = res.rows;
				})
			},
			// 查询条件时间选择
			timeChange(val) {
				this.queryParams.startTime = val[0] + " 00:00:00";
				this.queryParams.endTime = val[1] + " 23:59:59";
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					expenseId: null,
					recordId: null,
					file: null,
					fileName: null,
					createdTime: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.timeData = [];
				this.queryParams.startTime = null;
				this.queryParams.endTime = null;
				this.queryParams.contractCode = null;
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.selectedList = selection
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加报销附件";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids
				getBxExpenseFile(id).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改报销附件";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.id != null) {
							updateBxExpenseFile(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addBxExpenseFile(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除报销附件编号为"' + ids + '"的数据项？').then(function() {
					return delBxExpenseFile(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('business/bxExpenseFile/export', {
					...this.queryParams
				}, `bxExpenseFile_${new Date().getTime()}.xlsx`)
			},
			// PDF预览
			PdfPreview(val) {
				this.filePdfUrl = val;
				this.filePdfShow = true;
			},
			// 下载文件
			handleFileDownload(row) {
				return fetch(this.upload.baseUrl + row.file).then((res) =>
					res.blob().then((blob) => {
						let a = document.createElement("a");
						let url = window.URL.createObjectURL(blob);
						a.href = url;
						a.download = row.fileName;
						a.click();
						window.URL.revokeObjectURL(url);
					})
				);
			},
			//下载文件
			handleDownload(row){		
				const ids = row.id || this.ids;
				let allData = this.selectedList
				
						
				
				//获取时间
				let yy = new Date().getFullYear();
				let mm = new Date().getMonth()+1;
				let dd = new Date().getDate();


				//压缩转二进制流函数
				const zip = new JSZip();
				const blogTitle = yy+'-'+mm+'-'+dd+'.zip'
				const cache = {};
				const promises = [];
				//
				allData.forEach(item=>{				
					var url = this.upload.baseUrl  + item.file
					const promise = this.getFile(url).then(data=>{
						// *下载文件, 并存成ArrayBuffer对象
						const fileName = item.fileName
						zip.file(fileName, data, { binary: true })
						cache[fileName] = data;
					})
					promises.push(promise);				
				})
				Promise.all(promises).then(()=>{
					zip.generateAsync({
						type: "blob", compression: 'DEFLATE', // *STORE: 默认不压缩; DEFLATE：需要压缩
						compressionOptions: {
							level: 9 // *压缩等级 1~9。1: 压缩速度最快，9: 最优压缩方式
						}
					}).then(content=>{
						saveAs(content, blogTitle); // *生成二进制流，利用file-saver保存文件，文件名自定义
					})
				})

					
			},
			//接上条，获取文件下载
			getFile(url) {
				return new Promise((resolve, reject) => {
					//通过请求获取文件blob格式
					let xmlhttp = new XMLHttpRequest();
					xmlhttp.open("GET", url, true);
					xmlhttp.responseType = "blob";
					xmlhttp.onload = function () {
					if (xmlhttp.status == 200) {
						resolve(xmlhttp.response);
					} else {
						reject(xmlhttp.response);
					}
					};
					xmlhttp.send();
				});
			},

		}
	};
</script>


<style lang="scss" scoped>
	.file-pdf {
		cursor: pointer;
	}

	.file-pdf img {
		width: 50px;
		height: 50px;
	}

	::v-deep .pdfPreview {
		width: 100vw;
		height: 100vh;
		margin-top: 0 !important;
		background-color: rgb(82, 86, 89);

		.el-dialog__title {
			color: #f3f3f3;
		}


		.el-dialog__body {
			width: 100%;
			height: calc(100% - 54px);
		}

		.el-dialog__body iframe {
			width: 100%;
			height: 100%;
		}

		.el-dialog__headerbtn .el-dialog__close {
			color: #f3f3f3 !important;
		}
	}
</style>